package com.example.partner.activity.my;
import static android.content.ContentValues.TAG;
import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.partner.R;
import com.example.partner.common.BaseResponse;
import com.example.partner.model.domain.User;
import com.example.partner.adapter.user.TagsAdapter;
import com.example.partner.service.OssService;
import com.example.partner.service.UserService;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PersonDetailActivity extends AppCompatActivity {
    final String TAG = "PersonDetailActivity";
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 100;

    private static final int STORAGE_PERMISSION_REQUEST_CODE = 101;

    private static final int REQUEST_CODE_IMAGE_PICKER = 100;

    Uri photoUri;

    private ImageView imageViewAvatar;
    private ImageView back,save;
    private EditText editTextNickname;
    private EditText editTextProfile;
    private EditText editTextPhone;
    private EditText editTextEmail;
    private RadioGroup radioGroupGender;
    private RecyclerView recyclerView;
    private EditText editTextSelectedTags;
    private UserService userService;
    private OssService ossService;
    File imageFile;
    String uploadedUrl;


    private TagsAdapter adapter;
    private static final int PICK_IMAGE_REQUEST = 1;
    private static final int TAKE_PHOTO_REQUEST = 2;

    @Override
    public SharedPreferences getSharedPreferences(String name, int mode) {
        return super.getSharedPreferences(name, mode);
    }

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_detail);
        imageViewAvatar = findViewById(R.id.imageView_avatar);
        editTextNickname = findViewById(R.id.editText_nickname);
        editTextProfile = findViewById(R.id.editText_bio);
        editTextPhone = findViewById(R.id.editText_phone);
        editTextEmail = findViewById(R.id.editText_email);
        radioGroupGender = findViewById(R.id.radioGroup_gender);
        recyclerView = findViewById(R.id.recyclerview_tags);
        editTextSelectedTags = findViewById(R.id.editText_tags);
        save = findViewById(R.id.save);
        back = findViewById(R.id.back);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) // 更换为您的服务器URL
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        userService = retrofit.create(UserService.class);
        ossService = retrofit.create(OssService.class);




        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        // 假设 tags 是您的标签数组
        String[] tags = {"Java", "Python","建模","美妆","美食","旅游"};
        adapter = new TagsAdapter(tags);
        recyclerView.setAdapter(adapter);
        showUserDetail();
        adapter.setOnTagSelectedListener(selectedTags -> {
            editTextSelectedTags.setText(TextUtils.join(", ", selectedTags));
        });

        // 设置头像点击事件
        imageViewAvatar.setOnClickListener(v -> {
            // 选择头像逻辑
            selectAvatar();
        });
        showSelectedTags();
        back.setOnClickListener(view -> {
            // 处理点击事件
            finish(); // 关闭当前 Activity，返回上一页
        });

        save.setOnClickListener(view -> {
            // 处理点击事件
            saveUser();
        });
    }





    // 获取用户选择的性别
    private String getSelectedGender() {
        int selectedId = radioGroupGender.getCheckedRadioButtonId();
        // 确保选中了某个 RadioButton
        if (selectedId != -1) {
            RadioButton selectedRadioButton = findViewById(selectedId);
            // 检查 RadioButton 是否为 null
            if (selectedRadioButton != null) {
                return selectedRadioButton.getText().toString();
            }

        }
            // 没有选中任何 RadioButton，可以返回默认值或处理这种情况
              return "男"; // 或其他适当的处理

    }

    // 获取用户输入的昵称
    private String getUsername() {
        return editTextNickname.getText().toString();
    }

    // 获取用户输入的简介
    private String getProfile() {
        return editTextProfile.getText().toString();
    }

    // 获取用户输入的电话
    private String getPhone() {
        return editTextPhone.getText().toString();
    }

    // 获取用户输入的电话
    private String getEmail() {
        return editTextEmail.getText().toString();
    }
    private String getTags() {
        return editTextSelectedTags.getText().toString();
    }



    // 在适当的时机，例如表单提交时，保存用户信息
    private void saveUser() {
        int sex = 0;
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        Long userId = sharedPreferences.getLong("userId", -1);
        String username = getUsername();
        String profile = getProfile();
        String gender = getSelectedGender();
        if ("女".equals(gender)){
            sex = 1;
        }

        String phone = getPhone();
        String email = getEmail();
        String[] tags = getTags().split(",");
        List<String> list = Arrays.asList(tags);
        User request = new User(userId,username,profile,sex,phone,email,list.toString());

        userService.updateUser(request).enqueue(new Callback<BaseResponse<Integer>>() {
            @Override
            public void onResponse(Call<BaseResponse<Integer>> call, Response<BaseResponse<Integer>> response) {
                BaseResponse<Integer> responseBody = response.body();
                if (responseBody != null){
                    if (response.isSuccessful()) {
                        Toast.makeText(PersonDetailActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
                        updateSharedPreferences(request);
                        finish();
                    } else {
                        // 处理错误情况
                    }
                }

            }



            @Override
            public void onFailure(Call<BaseResponse<Integer>> call, Throwable t) {
                // 网络错误处理
                Log.e(TAG, "post回调失败：" + t.getMessage() + "," + t.toString());
                Toast.makeText(PersonDetailActivity.this, t.getMessage()+"post回调失败", Toast.LENGTH_SHORT).show();
            }
        });




        // 处理保存逻辑，可能需要存储到 SharedPreferences, 数据库, 或发送到服务器
    }



    // 更新 SharedPreferences 中的用户信息
    private void updateSharedPreferences(User user) {
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("username", user.getUsername());
        editor.putString("userAccount", user.getUserAccount());
        editor.putString("profile", user.getProfile());
        editor.putString("phone", user.getPhone());
        editor.putString("email", user.getEmail());
        editor.putString("avatar", uploadedUrl);
        editor.apply();
    }


    private void uploadAvatar(Uri imageUri) {
        imageFile = getFileFromUri(imageUri); // 从Uri转换为File对象的方法
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", imageFile.getName(), requestFile);

        Call<BaseResponse<String>> call = ossService.uploadOssFile(body);
        call.enqueue(new Callback<BaseResponse<String>>() {
            @Override
            public void onResponse(Call<BaseResponse<String>> call, Response<BaseResponse<String>> response) {
                if(response.isSuccessful()) {
                    uploadedUrl = response.body().getData();
                    Log.d(TAG, "文件上传成功: " + uploadedUrl);
                    Glide.with(PersonDetailActivity.this).load(uploadedUrl).into(imageViewAvatar);

                    // 更新 UI 或者 SharedPreferences
                } else {
                    Log.e(TAG, "文件上传失败: " + response.errorBody().toString());
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<String>> call, Throwable t) {
                Log.e(TAG, "文件上传异常", t);
            }
        });
    }

    private File getFileFromUri(Uri uri) {
        String filePath = null;
        if (uri != null && "content".equals(uri.getScheme())) {
            Cursor cursor = this.getContentResolver().query(uri, new String[] { MediaStore.Images.Media.DATA }, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    filePath = cursor.getString(columnIndex);
                }
                cursor.close();
            }
        } else if (uri != null && "file".equals(uri.getScheme())) {
            filePath = uri.getPath();
        }

        return filePath != null ? new File(filePath) : null;
    }


    private void requestCameraPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA},
                CAMERA_PERMISSION_REQUEST_CODE);
    }




    // 辅助方法：从 Uri 获取文件路径
    private String getRealPathFromURI(Uri contentUri) {
        String result;
        Cursor cursor = getContentResolver().query(contentUri, null, null, null, null);
        if (cursor == null) {
            result = contentUri.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }


    public void showUserDetail(){
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        String username = sharedPreferences.getString("username", "defaultUsername");
        String userProfile = sharedPreferences.getString("profile", "defaultUserProfile");
        String userPhone = sharedPreferences.getString("phone", "defaultPhone");
        String tags = sharedPreferences.getString("tags", "defaultTags");
        String email = sharedPreferences.getString("email", "defaultEmail");
        String avatar = sharedPreferences.getString("avatar", "");
        Glide.with(this).load(avatar).into(imageViewAvatar);
        editTextNickname.setText(username);
        editTextProfile.setText(userProfile);
        editTextPhone.setText(userPhone);
        editTextEmail.setText(email);


    }


    private void showSelectedTags() {
        ArrayList<String> selectedTags = adapter.getSelectedTags();
        editTextSelectedTags.setText(TextUtils.join(", ", selectedTags));
    }

    // 在 onResume() 方法中更新用户信息显示
    @Override
    protected void onResume() {
        super.onResume();
        showUserDetail();
    }
    private void updateSharedPreferencesForAvatar(String avatarUrl) {
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("avatar", avatarUrl);
        editor.apply();
    }

    private boolean checkCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    private void selectAvatar() {
        final CharSequence[] items = {"从相册选择", "拍照", "取消"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("更换头像");
        builder.setItems(items, (dialog, item) -> {
            if (items[item].equals("从相册选择")) {
                // 相册选择逻辑
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                startActivityForResult(intent, REQUEST_CODE_IMAGE_PICKER);

            } else if (items[item].equals("拍照")) {
                if (checkCameraPermission() && checkStoragePermission()) {
                    openCamera();
                } else {
                    requestCameraPermission();
                    requestStoragePermission();
                }
            } else if (items[item].equals("取消")) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // 错误处理
            }
            if (photoFile != null) {
                photoUri = FileProvider.getUriForFile(this, "com.example.partner.fileprovider", photoFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(intent, TAKE_PHOTO_REQUEST);
            }
        }
    }

    private boolean checkStoragePermission() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED;
    }

    private void requestStoragePermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                STORAGE_PERMISSION_REQUEST_CODE);
    }
    // 获取文件的实际路径
    private String getRealPathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor == null) return null;
        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }
    // 上传图片到服务器
    private void uploadImageToServer(File imageFile) {
        // 创建RequestBody
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
        // 创建MultipartBody.Part，用于包装文件数据
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", imageFile.getName(), requestFile);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        OssService ossService = retrofit.create(OssService.class);
        // 构建请求
        Call<BaseResponse<String>> call = ossService.uploadOssFile(filePart);
        // 发送请求
        call.enqueue(new Callback<BaseResponse<String>>() {
            @Override
            public void onResponse(Call<BaseResponse<String>> call, Response<BaseResponse<String>> response) {
                if (response.isSuccessful()) {
                    // 处理成功响应
                    System.out.println("添加成功");
                    String url = response.body().getData();
                    Glide.with(PersonDetailActivity.this).load(url).into(imageViewAvatar);
                } else {
                    // 处理错误响应
                    System.out.println("上传图片失败");
                    Log.d(TAG, "onResponse: upload fail");
                }
            }
            @Override
            public void onFailure(Call<BaseResponse<String>> call, Throwable t) {
                t.printStackTrace();                // 处理请求失败
                System.out.println("上传图片网络请求失败");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            // 4. 将Uri转换为文件路径
            if (imageUri != null) {
                // 接下来，使用 imageUri 进行操作
                String filePath = getRealPathFromUri(imageUri);
                if (filePath != null) {
                    File imageFile = new File(filePath);
                    uploadImageToServer(imageFile);
                }
            } else {
                // 处理返回的 Uri 为空的情况
                Toast.makeText(this, "图片未选择或路径错误", Toast.LENGTH_SHORT).show();
            }
        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (checkStoragePermission()) {
                    openCamera();
                } else {
                    requestStoragePermission();
                }
            }
        } else if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (checkCameraPermission()) {
                    openCamera();
                }
            }
        }
    }


    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );
        return image;
    }





}